package com.simpleapps.bfpcalc;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class SimpleBFPActivity extends Activity {
	
	private boolean kg = true;
	private boolean cm = true;
	
	private final float underWeightMax = 18.49f;
	private final float normalWeightMax = 24.99f;
	private final float overWeightMax = 29.99f;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
      //initiate spinner
      		Spinner weight_spinner = (Spinner) findViewById(R.id.weight_spinner);
      		ArrayAdapter<CharSequence> weight_adapter = ArrayAdapter
      				.createFromResource(this, R.array.weights_array,
      						android.R.layout.simple_spinner_item);
      		weight_adapter
      				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
      		weight_spinner.setAdapter(weight_adapter);
      		weight_spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

      			@Override
      			public void onItemSelected(AdapterView<?> parent, View view,
      					int pos, long id) {
      				if (!parent.getItemAtPosition(pos).toString().equals("kg"))
      					kg = false;
      				else
      					kg = true;
      			}

      			@Override
      			public void onNothingSelected(AdapterView<?> arg0) {
      			}
      		});

      		Spinner height_spinner = (Spinner) findViewById(R.id.height_spinner);
      		ArrayAdapter<CharSequence> height_adapter = ArrayAdapter
      				.createFromResource(this, R.array.heights_array,
      						android.R.layout.simple_spinner_item);
      		height_adapter
      				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
      		height_spinner.setAdapter(height_adapter);
      		height_spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

      			@Override
      			public void onItemSelected(AdapterView<?> parent, View view,
      					int pos, long id) {
      				if (!parent.getItemAtPosition(pos).toString().equals("cm"))
      					cm = false;
      				else
      					cm = true;
      			}

      			@Override
      			public void onNothingSelected(AdapterView<?> arg0) {

      			}
      		});
      		
      		//show on load		
      		Toast.makeText(getApplicationContext(), getText(R.string.hello),
      				Toast.LENGTH_LONG).show();
    }
    
    public void calculateBFP(View v) {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

		EditText weight = (EditText) findViewById(R.id.weight);
		EditText height = (EditText) findViewById(R.id.height);
		EditText age = (EditText) findViewById(R.id.age);
		RadioGroup gender = (RadioGroup) findViewById(R.id.gender);
		
		//validations
		float fWeight;
		try {
			fWeight = Float.parseFloat(weight.getText().toString());
			if (fWeight <= 0f)
				throw new NumberFormatException();
		} catch (NumberFormatException e) {
			Toast.makeText(getApplicationContext(),
					"Please enter valid weight!", Toast.LENGTH_SHORT).show();
			e.printStackTrace();
			return;
		}
		float fHeight;
		try {
			fHeight = Float.parseFloat(height.getText().toString());
			if (fHeight <= 0f)
				throw new NumberFormatException();
		} catch (NumberFormatException e) {
			Toast.makeText(getApplicationContext(),
					"Please enter valid height!", Toast.LENGTH_SHORT).show();
			e.printStackTrace();
			return;
		}

		int iAge;
		try {
			iAge = Integer.parseInt(age.getText().toString());
			if (iAge <= 0)
				throw new NumberFormatException();
		} catch (NumberFormatException e) {
			Toast.makeText(getApplicationContext(),
					"Please enter valid age!", Toast.LENGTH_SHORT).show();
			e.printStackTrace();
			return;
		}
		
		int iGender;		
		if(gender.getCheckedRadioButtonId() == R.id.male)
			iGender = 1;
		else
			iGender = 0;
		
		//calculate bmi
		float bmi = 0;
		if (!cm)
			fHeight = (float) (fHeight * 2.54);
		if (!kg)
			fWeight = (float) (fWeight / 2.2);

		bmi = (float) (fWeight / (fHeight * fHeight * 0.0001));
		TextView bmi_result = (TextView) findViewById(R.id.bmi_result);
		bmi_result.setText("BMI: "
				+ String.valueOf(Math.round(bmi * 100.0) / 100.0));

		//get result string
		String state = "";
		int color = 0;
		if (bmi <= underWeightMax) {
			state = "Underweight";
			color = Color.RED;
		} else if (bmi <= normalWeightMax) {
			state = "Normal Weight";
			color = Color.GREEN;
		} else if (bmi <= overWeightMax) {
			state = "Overweight";
			color = Color.rgb(255, 128, 64);
		} else {
			state = "Obese";
			color = Color.RED;
		}
		
		TextView bmi_status = (TextView) findViewById(R.id.bmi_status);
		bmi_status.setText("You are in " + state + " category.");
		bmi_status.setTextColor(color);
		
		//body fat
		float bodyFat;
		if(iAge <=18)
			bodyFat = (float) (1.51*bmi - 0.7*iAge - 3.6*iGender + 1.4);
		else
			bodyFat = (float) (1.20*bmi + 0.23*iAge - 10.8*iGender - 5.4);
		
		TextView bfp_status = (TextView) findViewById(R.id.bfp_status);
		bfp_status.setText("Your Body Fat is " + String.valueOf(Math.round(bodyFat * 100.0) / 100.0) + " %.");
		bfp_status.setTextColor(color);
		
		//normal weight range
		int normalWtMin = (int) ((underWeightMax + 0.01) * fHeight * fHeight) / (100*100);
		int normalWtMax = (int) ((normalWeightMax - 0.01) * fHeight * fHeight) / (100*100);
		
		TextView normal_wt = (TextView) findViewById(R.id.normal_wt);
		normal_wt.setText("Normal Weight Range: " + String.valueOf(normalWtMin) 
				+" - " +String.valueOf(normalWtMax) + " kgs.");
		normal_wt.setTextColor(Color.GREEN);
	}
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.bmi_values:
           // newGame();
            return true;
        case R.id.help:
            //showHelp();
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
}